import React, {lazy, Suspense, useMemo} from "react";
import "./App.css";
import {Navigate, Outlet, Route, Routes} from "react-router-dom";
import {businessRouter} from "@/route";
import Home from "@/page/Home"; // 保持同步加载

const PhotographyShowcase = lazy(() => import("@/page/Home/newIndex"));

const Login = lazy(() => import("@/page/User/Login"));
const AiWriting = lazy(() => import("@/page/Ai/Writing"));
const GradeSelection = lazy(() => import("@/page/Ai/Zite/GradeSelection"));
const PoemRecommendations = lazy(() => import("@/page/Ai/Zite/PoemRecommendations"));
const PrintPreview = lazy(() => import("@/page/Ai/Zite/PrintPreview"));
const Dialog = lazy(() => import("@/page/Ai/Zite/Dialog"));
const VisitorAuth = lazy(() => import("@/component/VisitorAuth"));
const Layout = lazy(() => import("@/component/Layout"));
const Authorized = lazy(() => import("@/component/Authorized"));
const NotFound = lazy(() => import("@/page/NotFound"));
const ToyHome = lazy(() => import("@/page/Toy/Home"));
const Detail = lazy(() => import("@/page/Toy/Detail"));

function RenderRoute(routeList: any): any {
  return routeList.map((item: any) => {
    if (item.hasOwnProperty("children")) {
      return RenderRoute(item.children);
    } else {
      return <Route path={item.path} key={item.name} element={item.element()} />;
    }
  });
}

function App(): JSX.Element {
  return useMemo(
    () => (
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path={"/"} element={<PhotographyShowcase />} />
          <Route
            element={
              <VisitorAuth>
                <Outlet />
              </VisitorAuth>
            }
          >
            <Route path={"/toy"}>
              <Route index element={<Navigate to="home" replace />} />
              <Route path={"home"} element={<ToyHome />} />
              <Route path={"detail/:id"} element={<Detail />} />
            </Route>
            <Route path={"/ai"}>
              <Route path={"writing"} element={<AiWriting />} />
              <Route path={"zite"}>
                <Route index element={<Navigate to="gradeSelection" replace />} />
                <Route path={"gradeSelection"} element={<GradeSelection />} />
                <Route path={"poemRecommendations"} element={<PoemRecommendations />} />
                <Route path={"printPreview"} element={<PrintPreview />} />
                <Route path={"dialog"} element={<Dialog />} />
              </Route>
            </Route>
          </Route>

          <Route path={"/user"}>
            <Route path={"login"} element={<Login />} />
          </Route>

          <Route
            element={
              <Authorized>
                <Layout />
              </Authorized>
            }
          >
            {RenderRoute(businessRouter)}
          </Route>
          <Route path={"*"} element={<NotFound />} />
        </Routes>
      </Suspense>
    ),
    []
  );
}

export default App;
